﻿
using System.Security.Cryptography;

namespace Timo.Common.Extension;

/// <summary>
/// MD5加密
/// </summary>
public static class MD5EncryptHelper
{
    /// <summary>
    /// MD5字符串加密
    /// </summary>
    /// <param name="str"></param>
    /// <param name="to_upper">是否转大写。默认小写</param>
    /// <returns>加密后字符串</returns>
    public static string MD5Encrypt(this string str,bool to_upper = false)
    {
        if(string.IsNullOrEmpty(str) || string.IsNullOrWhiteSpace(str))
            return string.Empty;
        using (MD5 mi = MD5.Create())
        {
            byte[] buffer = Encoding.Default.GetBytes(str);
            //开始加密
            byte[] newBuffer = mi.ComputeHash(buffer);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < newBuffer.Length; i++)
            {
                if(to_upper)
                    sb.Append(newBuffer[i].ToString("X2"));
                else
                    sb.Append(newBuffer[i].ToString("x2"));
            }
            return sb.ToString();
        }
    }

    /// <summary>
    /// MD5哈希值校验
    /// </summary>
    /// <param name="str">原文</param>
    /// <param name="hash">MD5值</param>
    /// <returns></returns>
    public static bool MD5ValidateHash(this string str,string hash)
    {
        var res = false;
        var s = string.Empty;
        if (string.IsNullOrEmpty(str) || string.IsNullOrWhiteSpace(str) || string.IsNullOrEmpty(hash) || string.IsNullOrWhiteSpace(hash))
            return res;
        s = s.MD5Encrypt();
        if (s.Equals(hash))
            return res = true;
        s = s.MD5Encrypt(true);
        if (s.Equals(hash))
            return res = true;
        return res;
    }

}
